import React, { Component } from "react";
import {
  Button,
  Form,
  Input,
  Switch,
  message,
  Spin,
  Modal,
  Row,
  Col,
  Divider,
  Table
} from "antd";
import { connect } from "dva";
import moment from "moment";
import dataInfo from "./data";
import BottomInfo from "./components/BottomInfo";
import styles from "./MessageAdd.less";
import FixedBottomWrapper from "../../../components/FixedBottomWrapper";
import { getTemplateDetail } from "../services/messageTemplateApi";
import preview from "../../../assets/preview.png";
import {
  msgSceneColumn,
  msgTmpColumn,
  msgReceiveColumn,
  msgChannelColumn
} from "./columns";
import SelectMsgTmpModal from "./components/msgTmpModal";
import SelectReceiveModal from "./components/ReceiveModal";
import SelectChannelModal from "./components/channelModal";
import SelectSceneModal from "./components/sceneModal";
import { getChannelText } from "../../channelType";

@connect(stores => ({
  coldata: stores.user,
  dsDetail: stores.adddataSource,
  messageSave: stores.saveMessage,
  EditplanData: stores.addPlan,
  channelDictionaryModel: stores.channelDictionaryModel
}))
@Form.create()
class MessageAdd extends Component {
  state = {
    workDisable: true,
    startTime: "",
    endTime: "",
    category: 1,
    num: "",
    workTime: "",
    ruleType: "",
    ruleDisable: true,
    ruleChannel: "",
    ownerDeptName: "",
    manager: [],
    managerName: [],
    timeVisible: false,
    radioVisible: false,
    msgSourceId: "",
    loadingEdit: false,
    ownerDept: "",
    channelName: "",
    channleType: null,
    resendChannelName: "",
    messageType: null,
    isUseTemplate: false,
    templateList: [],
    initChannelType: null,
    initTemplateItem: null,
    // 新增模板弹框状态
    msgTmpModalVisible: false,
    tmpsOfSelected: [],
    // 新增接收组弹框状态
    receiveModalVisible: false,
    receivesOfSelected: [],
    // 新增渠道弹框状态
    channelModalVisible: false,
    channelsOfSelected: [],
    // 新增渠道弹框状态
    sceneModalVisible: false,
    scenesOfSelected: [],
    // 模板预览
    previewTmpVisible: false,
    previewTmpContent: "",

    failureResendInterval: "",
    failureResendTimes: ""
  };

  componentDidMount() {
    setTimeout(() => {
      this.setValue();
    }, 500);
  }

  setValue = () => {
    const { messageSave } = this.props;
    const { key } = messageSave;
    const {
      coldata: {
        userInfo: {
          userId = "",
          userName = "",
          department = "",
          departmentName = ""
        } = {}
      } = {},
      dispatch
    } = this.props;
    window.console.log(key.operate);
    if (key.operate)
      if (key.operate === "add") {
        this.setState({
          manager: [userId],
          managerName: [userName],
          ownerDept: department,
          ownerDeptName: departmentName
        });
        this.props.form.setFieldsValue({ owner: 1 });
      }
    if (key.operate === "mod") {
      this.setState({ loadingEdit: true });
      dispatch({
        type: "saveMessage/getDetail",
        payload: { msgSourceId: key.msgSourceId }
      }).then(() => {
        this.getDetail(key.msgSourceId);
      });
    }
  };

  getDetail = async msgSourceId => {
    const { messageSave } = this.props;
    const { detailMessage = {} } = messageSave;
    const { workTime } = dataInfo.setWork(detailMessage);

    let ruleType = "";
    if (
      detailMessage.resendChannelId &&
      detailMessage.resendChannelId === detailMessage.pushChannelId
    ) {
      ruleType = 1;
    } else if (
      detailMessage.resendChannelId &&
      detailMessage.resendChannelId !== "" &&
      detailMessage.resendChannelId !== detailMessage.pushChannelId
    ) {
      ruleType = 2;
    } else {
      ruleType = "";
    }
    const isUseTemplate = typeof detailMessage.primaryId === "number";
    const initTemplateItem = {
      id: detailMessage.primaryId,
      name: detailMessage.templateName
    };
    this.setState(
      {
        workTime,
        startTime: workTime === 6 ? detailMessage.startTime : "",
        endTime: workTime === 6 ? detailMessage.endTime : "",
        workDisable: workTime !== 6,
        channelName: detailMessage.pushChannelName
          ? detailMessage.pushChannelName
          : "",
        category: !detailMessage.flowControlTimeUnit
          ? 1
          : detailMessage.flowControlTimeUnit,
        num: !detailMessage.flowControlCountLimit
          ? ""
          : detailMessage.flowControlCountLimit,
        manager: [
          detailMessage.owner && JSON.parse(detailMessage.owner)
            ? JSON.parse(detailMessage.owner)[0].key
            : ""
        ],
        managerName: [
          detailMessage.owner && JSON.parse(detailMessage.owner)
            ? JSON.parse(detailMessage.owner)[0].name
            : ""
        ],
        ownerDept: detailMessage.ownerDept,
        ownerDeptName: detailMessage.ownerDeptName,
        msgSourceId,
        ruleChannel: ruleType === 1 ? "" : detailMessage.resendChannelId,
        resendChannelName: detailMessage.resendChannelName,
        ruleType,
        ruleDisable:
          detailMessage.resendChannelId === detailMessage.pushChannelId ||
          !detailMessage.resendChannelId ||
          detailMessage.resendChannelId === "",
        channelType: detailMessage.pushChannelType,
        initChannelType: detailMessage.pushChannelType,
        isUseTemplate,
        initTemplateItem: isUseTemplate ? initTemplateItem : null,
        failureResendTimes: detailMessage.failureResendTimes,
        failureResendInterval: detailMessage.failureResendInterval,
        // 场景
        scenesOfSelected: detailMessage.sceneCode
          ? [
              {
                sourceCode: detailMessage.messageCode,
                sourceName: detailMessage.messageName,
                sceneCode: detailMessage.sceneCode,
                sceneName: detailMessage.sceneName,
                haveChannel: detailMessage.haveChannel,
                haveTemplate: detailMessage.haveTemplate,
                haveGroup: detailMessage.haveGroup
              }
            ]
          : [],
        // 消息模板
        tmpsOfSelected: detailMessage.templateCode
          ? [
              {
                templateCode: detailMessage.templateCode,
                templateName: detailMessage.templateName,
                templateTitle: detailMessage.templateTitle,
                templateContent: detailMessage.templateContent
              }
            ]
          : [],
        // 接收组
        receivesOfSelected: detailMessage.receiveGroupCode
          ? [
              {
                receiveGroupCode: detailMessage.receiveGroupCode,
                receiveGroupName: detailMessage.receiveGroupName
              }
            ]
          : [],
        // 渠道
        channelsOfSelected: detailMessage.pushChannelList
      },
      () => {
        setTimeout(() => {
          this.props.form.setFieldsValue({
            owner: 1,
            sourceCode: detailMessage.sourceCode,
            messageName: detailMessage.sourceName,
            messageType: detailMessage.messageType,
            templatePrimaryId: detailMessage.primaryId,
            templateId: detailMessage.templateId,
            channelType: String(detailMessage.pushChannelType),
            channelName: detailMessage.pushChannelId,
            messageDescription: detailMessage.sourceDescription,
            isEnabled: detailMessage.isEnabled === "Y"
          });
          this.setState({ loadingEdit: false });
        }, 200);
      }
    );
  };

  handleSubmit = e => {
    const {
      workTime,
      startTime,
      endTime,
      num,
      ownerDeptName,
      category,
      manager,
      managerName,
      msgSourceId,
      // channelName,
      channelsOfSelected,
      tmpsOfSelected,
      scenesOfSelected,
      receivesOfSelected,
      failureResendTimes,
      failureResendInterval
    } = this.state;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (workTime === "") {
        this.setState({
          radioVisible: true
        });
        return;
      }
      if (workTime === 6 && startTime === "") {
        this.setState({
          timeVisible: true
        });
        return;
      }

      if (!err) {
        const { dispatch } = this.props;
        // 判断场景不能为空
        if (scenesOfSelected.length === 0) {
          message.error("消息场景不能为空");
          return;
        }
        const payload = {
          msgSourceId,
          sourceName: values.messageName,
          sourceCode: values.sourceCode,
          ownerRequest: [{ key: manager[0], name: managerName[0] }],
          ownerDept: values.ownerDept,
          sourceDescription: values.messageDescription,
          flowControlTimeUnit: category,
          flowControlCountLimit: num,
          ownerDeptName,
          // pushChannelName: channelName,
          // resendChannelId,
          messageType: values.messageType,
          // resendChannelName: resendChannelTmp,
          sourceType: workTime,
          startTime: dataInfo.workTimeClassify(workTime, startTime, endTime)
            .startTime,
          endTime: dataInfo.workTimeClassify(workTime, startTime, endTime)
            .endTime,
          // templatePrimaryId: isUseTemplate ? values.templatePrimaryId : null,
          // sourceId: values.sourceId,
          isEnabled: values.isEnabled ? "Y" : "N",
          // 渠道ids
          // pushChannelType: values.channelType,
          pushChannelIds: channelsOfSelected.map(l => l.pushChannelId),
          pushChannelCode: channelsOfSelected
            .map(l => l.channelCode)
            .join(","),
          pushChannelName: channelsOfSelected
            .map(l => l.description)
            .join(","),
          failureResendTimes,
          failureResendInterval,
          // 模板
          templateId:
            tmpsOfSelected.length > 0 ? tmpsOfSelected[0].templateId : "",
          templateCode:
            tmpsOfSelected.length > 0 ? tmpsOfSelected[0].templateCode : "",
          templateName:
            tmpsOfSelected.length > 0 ? tmpsOfSelected[0].templateName : "",
          // 场景
          messageCode:
            scenesOfSelected.length > 0 ? scenesOfSelected[0].sourceCode : "",
          messageName:
            scenesOfSelected.length > 0 ? scenesOfSelected[0].sourceName : "",
          sceneCode:
            scenesOfSelected.length > 0 ? scenesOfSelected[0].sceneCode : "",
          sceneName:
            scenesOfSelected.length > 0 ? scenesOfSelected[0].sceneName : "",
          // 接收组
          receiveGroupCode:
            receivesOfSelected.length > 0
              ? receivesOfSelected[0].receiveGroupCode
              : ""
        };
        dispatch({
          // type:
          //   key.operate === "add"
          //     ? "saveMessage/saveSendMessage"
          //     : "saveMessage/editMessage",
          type: "saveMessage/saveSendMessage",
          payload
        }).then(res => {
          const { errCode, errMsg } = res;
          if (errCode === 0) {
            const { history } = this.props;
            message.success("操作成功");
            history.push("/messageCenter/messageManager/messageSource");
          } else {
            message.error(errMsg);
          }
        });
      }
    });
  };

  getChannel = e => {
    const { EditplanData } = this.props;
    const { channelList = [] } = EditplanData;
    let channelName = "";
    channelList.forEach(item => {
      if (String(item.pushChannelId) === String(e)) {
        channelName = item.description;
      }
    });
    this.setState({
      ruleChannel: e,
      resendChannelName: channelName
    });
  };

  getRule = e => {
    this.setState({
      ruleType: e.target.value,
      ruleDisable: e.target.value !== 2
    });
  };

  getTimeCategory = e => {
    this.setState({
      category: e
    });
  };

  getNumber = e => {
    this.setState({
      num: e
    });
  };

  failureResendIntervalChange = e => {
    this.setState({
      failureResendInterval: e
    });
  };

  failureResendTimesChange = e => {
    this.setState({
      failureResendTimes: e
    });
  };

  onBack = () => {
    const { history } = this.props;
    history.goBack(-1);
    /*
    Modal.confirm({
      title: "是否直接关闭此消息源？",
      onOk() {
        history.push("/messageCenter/messageManager/messageSource");
      },
      onCancel() {}
    });
    */
  };

  getWorkTimeType = e => {
    this.setState({
      workTime: e.target.value,
      workDisable: e.target.value !== 6,
      radioVisible: false,
      timeVisible: false
    });
  };

  getWorkTime = self => {
    this.setState({
      startTime: moment(self[0]).format("YYYY-MM-DD HH:mm:ss"),
      endTime: moment(self[1]).format("YYYY-MM-DD HH:mm:ss"),
      timeVisible: false
    });
  };

  // 关闭选择模板弹框
  onTmpModalClose() {
    this.setState({
      msgTmpModalVisible: false
    });
  }

  // 设置state
  onSetState(key, value) {
    this.setState({
      [key]: value
    });
  }

  // 更改选择模板方法
  onMsgTmpSelectedChange = list => {
    this.setState({
      tmpsOfSelected: list
    });
  };

  // 预览模板
  onPreviewTmp = rec => {
    this.onSetState("previewTmpVisible", true);
    this.onSetState("previewTmpContent", "loading……");
    getTemplateDetail({ templateId: rec.templateId }).then(res => {
      if (res.success) {
        this.onSetState("previewTmpContent", res.datas.templateContent);
      }
    });
  };

  render() {
    const { EditplanData, channelTypeList, messageSave } = this.props;
    const { key } = messageSave;
    const { channelList = [] } = EditplanData;
    const { getFieldDecorator } = this.props.form;
    // const { orgTree = [] } = dsDetail;
    const { timeVisible } = this.state;
    const { radioVisible, loadingEdit } = this.state;
    const {
      workDisable,
      num,
      startTime,
      endTime,
      workTime,
      ruleDisable,
      ruleType,
      ruleChannel,
      category,
      msgTmpModalVisible,
      tmpsOfSelected,
      receiveModalVisible,
      receivesOfSelected,
      channelModalVisible,
      channelsOfSelected,
      sceneModalVisible,
      scenesOfSelected,
      previewTmpVisible,
      previewTmpContent,
      failureResendInterval,
      failureResendTimes
    } = this.state;
    const { formItemLayout } = dataInfo;
    // 场景column
    const sceneColumn = msgSceneColumn.concat([
      {
        title: "是否自带渠道",
        align: "center",
        render: (_, record) => (record.haveChannel === "Y" ? "是" : "否")
      },
      {
        title: "是否自带消息模板",
        align: "center",
        render: (_, record) => (record.haveTemplate === "Y" ? "是" : "否")
      },
      {
        title: "是否自带消息接收组",
        align: "center",
        render: (_, record) => (record.haveGroup === "Y" ? "是" : "否")
      }
    ]);
    // 消息模板column
    const tmpColumn = msgTmpColumn.concat([
      {
        title: "消息模板内容",
        render: (_, record) => (
          <a onClick={() => this.onPreviewTmp(record)}>查看</a>
        )
      }
    ]);
    // 渠道column
    const channelColumn = msgChannelColumn.concat([
      {
        title: "渠道类型",
        dataIndex: "channelType",
        render: text => getChannelText(channelTypeList, text)
      }
    ]);
    // 默认表格分页信息
    const pagation = {
      defaultPageSize: 5
    };

    return (
      <React.Fragment>
        <FixedBottomWrapper
          className={styles.root}
          footer={
            <div className={styles.btns}>
              <Button onClick={this.onBack}>取消</Button>
              <Button
                style={{ marginLeft: 8, marginRight: 8 }}
                type="primary"
                // htmlType="submit"
                onClick={e => this.handleSubmit(e)}
              >
                保存
              </Button>
            </div>
          }
        >
          <Spin spinning={loadingEdit}>
            <div className={styles.topInfo}>
              <span className={styles.basic}>基本信息</span>
              <div className={styles.formBox}>
                <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                  <Row>
                    <Col span={12}>
                      <Form.Item
                        {...formItemLayout}
                        label="发送任务编码"
                        span={12}
                      >
                        {getFieldDecorator("sourceCode", {
                          rules: [
                            {
                              required: true,
                              message: "发送任务编码不能为空"
                            }
                            // {
                            //   max: 20,
                            //   message: "发送任务编码少于20个字"
                            // }
                          ]
                        })(
                          <Input
                            disabled={key.operate === "mod"}
                            placeholder="请输入发送任务编码"
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item {...formItemLayout} label="发送任务名称">
                        {getFieldDecorator("messageName", {
                          rules: [
                            {
                              required: true,
                              message: "发送任务名称不能为空"
                            },
                            {
                              max: 20,
                              message: "发送任务名称少于20个字"
                            }
                          ]
                        })(<Input placeholder="请输入发送任务名称" />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={12}>
                      <Form.Item {...formItemLayout} label="是否启用">
                        {getFieldDecorator("isEnabled", {
                          valuePropName: "checked"
                        })(
                          <Switch checkedChildren="开" unCheckedChildren="关" />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
                <Divider style={{ marginTop: 0 }} />
                <Row>
                  <Col span={12}>
                    <Form.Item
                      {...formItemLayout}
                      labelAlign="left"
                      required
                      label="消息场景"
                    >
                      <Button
                        type="primary"
                        onClick={() =>
                          this.onSetState("sceneModalVisible", true)
                        }
                      >
                        重选
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
                <Table
                  scroll={{ x: "max-content" }}
                  size="small"
                  columns={sceneColumn}
                  dataSource={scenesOfSelected}
                  pagination={pagation}
                />
                <Row style={{ marginTop: 16 }}>
                  <Col span={12}>
                    <Form.Item
                      {...formItemLayout}
                      labelAlign="left"
                      label="消息模板"
                    >
                      <Button
                        type="primary"
                        onClick={() =>
                          this.onSetState("msgTmpModalVisible", true)
                        }
                      >
                        重选
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
                <Table
                  size="small"
                  columns={tmpColumn}
                  dataSource={tmpsOfSelected}
                  pagination={pagation}
                />
                <Row style={{ marginTop: 16 }}>
                  <Col span={12}>
                    <Form.Item
                      {...formItemLayout}
                      labelAlign="left"
                      label="消息接收组"
                    >
                      <Button
                        type="primary"
                        onClick={() =>
                          this.onSetState("receiveModalVisible", true)
                        }
                      >
                        重选
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
                <Table
                  size="small"
                  columns={msgReceiveColumn}
                  dataSource={receivesOfSelected}
                  pagination={pagation}
                />
                <Row style={{ marginTop: 16 }}>
                  <Col span={12}>
                    <Form.Item
                      {...formItemLayout}
                      labelAlign="left"
                      label="消息渠道"
                    >
                      <Button
                        type="primary"
                        onClick={() =>
                          this.onSetState("channelModalVisible", true)
                        }
                      >
                        重选
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
                <Table
                  size="small"
                  columns={channelColumn}
                  dataSource={channelsOfSelected}
                  pagination={pagation}
                />
              </div>
            </div>
            <BottomInfo
              getRule={this.getRule}
              getFlux={this.getFlux}
              getWorkTime={this.getWorkTime}
              getWorkTimeType={this.getWorkTimeType}
              workDisable={workDisable}
              getTimeCategory={this.getTimeCategory}
              getNumber={this.getNumber}
              num={num}
              startTime={startTime}
              endTime={endTime}
              workTime={workTime}
              ruleDisable={ruleDisable}
              ruleType={ruleType}
              category={category}
              ruleChannel={ruleChannel}
              timeVisible={timeVisible}
              radioVisible={radioVisible}
              channelList={channelList}
              getChannel={this.getChannel}
              failureResendInterval={failureResendInterval}
              failureResendIntervalChange={this.failureResendIntervalChange}
              failureResendTimes={failureResendTimes}
              failureResendTimesChange={this.failureResendTimesChange}
            />
          </Spin>
        </FixedBottomWrapper>
        {msgTmpModalVisible && (
          <SelectMsgTmpModal
            tmpsOfSelected={tmpsOfSelected}
            visible={msgTmpModalVisible}
            onClose={() => this.onSetState("msgTmpModalVisible", false)}
            onCheck={e => this.onSetState("tmpsOfSelected", e)}
          />
        )}
        {receiveModalVisible && (
          <SelectReceiveModal
            receivesOfSelected={receivesOfSelected}
            visible={receiveModalVisible}
            onClose={() => this.onSetState("receiveModalVisible", false)}
            onCheck={e => this.onSetState("receivesOfSelected", e)}
          />
        )}
        {channelModalVisible && (
          <SelectChannelModal
            channelsOfSelected={channelsOfSelected}
            visible={channelModalVisible}
            onClose={() => this.onSetState("channelModalVisible", false)}
            onCheck={e => this.onSetState("channelsOfSelected", e)}
          />
        )}
        {sceneModalVisible && (
          <SelectSceneModal
            scenesOfSelected={scenesOfSelected}
            visible={sceneModalVisible}
            onClose={() => this.onSetState("sceneModalVisible", false)}
            onCheck={e => this.onSetState("scenesOfSelected", e)}
          />
        )}

        <Modal
          className={styles.modal}
          visible={previewTmpVisible}
          title={false}
          footer={false}
          bodyStyle={{
            background: `url(${preview}) no-repeat`,
            backgroundSize: "241px 490px",
            backgroundPosition: "center center",
            padding: 0,
            display: "flex",
            justifyContent: "center"
          }}
          onCancel={() => this.onSetState("previewTmpVisible", false)}
          closable={false}
        >
          <div className={styles.preview}>
            <div className={styles.previewContent}>{previewTmpContent}</div>
          </div>
        </Modal>
      </React.Fragment>
    );
  }
}

export default connect(({ channelDictionaryModel }) => ({
  channelTypeList: channelDictionaryModel.channelsTypesData
}))(MessageAdd);
